package com.shi.shiro.shiro;

import cn.hutool.core.util.ObjUtil;
import com.shi.shiro.common.UserHolder;
import com.shi.shiro.domain.User;
import com.shi.shiro.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;

import javax.annotation.Resource;

@Slf4j
public class CustomerRealm extends AuthorizingRealm {

    @Resource
    private UserService userService;
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        log.info("用户授权...");
        User user = UserHolder.getUser();
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        user.getRoleList().forEach(role -> {
            info.addRole(role.getRoleName());
            role.getPermissionList().forEach(permission -> {
                info.addStringPermission(permission.getPermissionName());
            });
        });
        return info;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        log.info("用户认证...");
        String principal = token.getPrincipal().toString();
        User user = userService.getUserByUsername(principal);
        if (ObjUtil.isEmpty(user)){
            return null;
        }
        return new SimpleAuthenticationInfo(user,user.getPassword(), ByteSource.Util.bytes(user.getSalt()),getName());
    }
}
